<template>
  <div class="file-manager">
    <!-- 工具栏 -->
    <div class="toolbar-left-buttons">
      <el-button link @click="handleAddFiles">
        <el-icon class="margin-right-8px">
          <Plus />
        </el-icon>
        新建节点
      </el-button>
      <el-button link @click="handleImportData">
        <el-icon class="margin-right-8px">
          <Link />
        </el-icon>
        关联项目输入
      </el-button>
      <el-button link @click="handleOpenTask">
        <el-icon class="margin-right-8px">
          <FolderOpened />
        </el-icon>
        打开任务列表
      </el-button>
    </div>

    <!-- 文件列表表格 -->
    <div v-loading="loading" class="table-container">
      <CLTable
        :fields="fields"
        :initial-data="tableData as any"
        :line-height="currentLineHeight"
        :on-add-node="handleAddNode as any"
        :on-update-node="handleUpdateNode as any"
        :router-fields="routerFields"
        :more-actions="moreActions as any"
        :tableConfig="tableConfig"
        @update:initial-data="updateTableData as any"
        @view-node-detail="handleViewDetail as any"
        @show:records="handleShowRecords as any"
        @node-selected="handleNodeSelected as any"
        @onMoreAction="handleMoreAction as any"
      />
    </div>

    <!-- 文件上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文件"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            支持上传任意格式文件，单个文件不超过100MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUploadConfirm">
            确定上传
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from "vue";
  import {
    ElButton,
    ElDialog,
    ElUpload,
    ElIcon,
    ElMessage,
    ElMessageBox,
  } from "element-plus";
  import {
    Plus,
    Link,
    FolderOpened,
    UploadFilled,
  } from "@element-plus/icons-vue";
  import CLTable from "@/components/CLTable/index.vue";
  import { getReferenceFileList, deleteReferenceFile } from "@/api/reference";
  import type { ProjectSearchRequest } from "@/interface/project";
  import { Source } from "@/interface/task";

  interface FileNode {
    id: string;
    name: string;
    dataSource: string;
    dataFlow: string;
    dataSourceStatus: string;
    description?: string;
    size?: string;
    type?: string;
    uploadTime?: string;
    fileName?: string;
    children?: FileNode[];
  }

  interface Props {
    projectId?: string;
  }

  withDefaults(defineProps<Props>(), {
    projectId: "",
  });

  const emit = defineEmits<{
    (e: "file-uploaded", files: FileNode[]): void;
    (e: "file-deleted", fileId: string): void;
  }>();

  // 字段配置
  const fields = ref([
    {
      id: 1,
      name: "名称",
      field: "fileName",
      type: "text",
      invisible: true,
      width: 200,
    },
    {
      id: 2,
      name: "数据源",
      field: "source",
      type: "text",
      invisible: true,
      width: 150,
    },
    {
      id: 3,
      name: "数据流",
      field: "-",
      type: "text",
      invisible: true,
      width: 150,
    },
    {
      id: 4,
      name: "数据源状态",
      field: "-",
      type: "text",
      invisible: true,
      width: 150,
    },
  ]);

  // 路由字段
  const routerFields = ref(["name"]);

  // 更多操作配置
  const moreActions = ref([
    { label: "预览", key: "preview" },
    { label: "打开", key: "open" },
    { label: "复制", key: "copy" },
    { label: "关联", key: "link" },
    { label: "取消关联", key: "unlink" },
    { label: "删除", key: "del" },
  ]);

  // 表格配置
  const tableConfig = ref({
    // showOperationsColumn: false, // 是否显示操作列
    editable: false,
    // typeIconShow: false,
    rightFrozenColCount: 1,
    // OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    // OperationsColumnWidth: 320, //自定义操作列宽度
    borderMode: "none",
    tree: {
      enabled: true,
      column: 0,
      mode: "folder",
    },
    rowSeriesNumber: {
      enabled: true,
    },
  });

  // 表格数据
  const tableData = ref<FileNode[]>([]);

  // 加载状态
  const loading = ref(false);

  // 当前行高
  const currentLineHeight = ref<"low" | "medium" | "high" | "ultra-high">(
    "low",
  );

  // 上传对话框
  const uploadDialogVisible = ref(false);
  const uploadRef = ref();
  const fileList = ref<any[]>([]);

  // 添加文件
  const handleAddFiles = () => {
    uploadDialogVisible.value = true;
  };

  // 导入数据
  const handleImportData = () => {
    ElMessage.info("关联项目输入功能开发中");
  };

  // 打开任务列表
  const handleOpenTask = () => {
    ElMessage.info("打开任务列表功能开发中");
  };

  // 添加节点
  const handleAddNode = (parentNode: FileNode, newNode: FileNode) => {
    console.log("添加节点:", parentNode, newNode);
  };

  // 删除节点
  const handleDeleteNode = async (node: FileNode) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除文件"${node.name}"吗？`,
        "删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        },
      );

      await deleteReferenceFile(node.id);
      emit("file-deleted", node.id);
      ElMessage.success("文件删除成功");

      // 刷新文件列表
      await fetchFileList();
    } catch (error: any) {
      if (error !== "cancel") {
        console.error("删除文件失败:", error);
        ElMessage.error("删除文件失败");
      }
    }
  };

  // 更新节点
  const handleUpdateNode = (node: FileNode, field: string, value: any) => {
    console.log("更新节点:", node, field, value);
  };

  // 更新表格数据
  const updateTableData = (data: FileNode[]) => {
    tableData.value = data;
  };

  // 查看详情
  const handleViewDetail = (node: FileNode) => {
    console.log("查看详情:", node);
  };

  // 显示记录
  const handleShowRecords = (records: FileNode[]) => {
    console.log("显示记录:", records);
  };

  // 节点选择
  const handleNodeSelected = (nodes: FileNode[]) => {
    console.log("节点选择:", nodes);
  };

  // 更多操作
  const handleMoreAction = (action: string, node: FileNode) => {
    console.log("更多操作:", action, node);

    switch (action) {
      case "preview":
        ElMessage.info("预览功能开发中");
        break;
      case "open":
        ElMessage.info("打开功能开发中");
        break;
      case "copy":
        ElMessage.info("复制功能开发中");
        break;
      case "link":
        ElMessage.info("关联功能开发中");
        break;
      case "unlink":
        ElMessage.info("取消关联功能开发中");
        break;
      case "del":
        handleDeleteNode(node);
        break;
    }
  };

  // 文件改变
  const handleFileChange = (file: any, fileList: any[]) => {
    console.log("文件改变:", file, fileList);
  };

  // 确认上传
  const handleUploadConfirm = () => {
    const files = uploadRef.value?.uploadFiles || [];

    if (files.length === 0) {
      ElMessage.warning("请选择要上传的文件");
      return;
    }

    // 模拟上传
    const newFiles: FileNode[] = files.map((file: any, index: number) => ({
      id: `new-${Date.now()}-${index}`,
      name: file.name,
      dataSource: "本地上传",
      dataFlow: "-",
      dataSourceStatus: "-",
      type: file.name.split(".").pop() || "",
      size: formatFileSize(file.size),
    }));

    // 添加到输入数据节点
    const inputDataNode = tableData.value.find(
      (node) => node.name === "输入数据",
    );
    if (inputDataNode && inputDataNode.children) {
      inputDataNode.children.push(...newFiles);
    } else {
      tableData.value.push(...newFiles);
    }

    emit("file-uploaded", newFiles);
    ElMessage.success(`成功上传 ${files.length} 个文件`);

    uploadDialogVisible.value = false;
    fileList.value = [];
    uploadRef.value?.clearFiles();

    // 刷新文件列表
    fetchFileList();
  };

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return "0 B";
    const k = 1024;
    const sizes = ["B", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + " " + sizes[i];
  };

  // 获取文件列表数据
  const fetchFileList = async () => {
    loading.value = true;
    try {
      const params: ProjectSearchRequest = {
        pageNo: 1,
        pageSize: 999,
        conditions: [],
        logic: "AND",
        sortParams: [],
      };

      const response = await getReferenceFileList(params);
      const data = (response as any).data || response;
      const rawData = data.result || [];

      // 将接口数据转换为 FileNode 格式，空值显示为 "-"
      const convertedData: FileNode[] = rawData.map((item: any) => ({
        id: item.id || item.fileId || "",
        fileName: item.fileName,
        source: item.source === Source.Upload ? "本地上传" : item.source || "-",
        description: item.remark || item.description || "-",
        size: item.fileSize ? formatFileSize(item.fileSize) : "-",
        type: item.type || "-",
        uploadTime: item.createTime || item.uploadTime || "-",
      }));

      tableData.value = convertedData;

      console.log("文件列表加载成功:", tableData.value);
    } catch (error) {
      console.error("获取文件列表失败:", error);
      ElMessage.error("获取文件列表失败");
      // 使用空数据
      tableData.value = [];
    } finally {
      loading.value = false;
    }
  };

  // 组件挂载时获取数据
  onMounted(() => {
    fetchFileList();
  });

  // 暴露方法
  defineExpose({
    addFiles: () => {
      uploadDialogVisible.value = true;
    },
    getTableData: () => tableData.value,
    refresh: fetchFileList,
  });
</script>

<style scoped lang="scss">
  .file-manager {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: #fff;

    .toolbar-left-buttons {
      display: flex;
      gap: 8px;
      align-items: center;
      padding: 10px 0;
    }

    .table-container {
      flex: 1;
      overflow: hidden;
    }

    :deep(.el-button) {
      display: flex;
      align-items: center;
      gap: 4px;
    }

    .upload-demo {
      width: 100%;

      :deep(.el-upload-dragger) {
        width: 100%;
        padding: 40px;
      }
    }

    .el-icon--upload {
      font-size: 67px;
      color: #c0c4cc;
      margin-bottom: 16px;
    }

    .el-upload__text {
      color: #606266;
      font-size: 14px;
      text-align: center;

      em {
        color: #409eff;
        font-style: normal;
      }
    }

    .el-upload__tip {
      color: #909399;
      font-size: 12px;
      margin-top: 7px;
      text-align: center;
    }

    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
    }
  }

  .margin-right-8px {
    margin-right: 8px;
    display: inline-block;
    margin-top: -2px;
  }
</style>
